package org.ace.logic;

import io.netty.channel.Channel;

import javax.annotation.Resource;

import org.ace.endingCode.SocketModel;
import org.ace.event.model.OnShakeEvent;
import org.ace.logic.login.protocol.LoginProtocol;
import org.ace.nettyhandler.HeartBeatHandler;
import org.ace.protocol.Protocol;
import org.ace.tool.impl.ErrorUtil;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationListener;

public class LogicHandler implements IoHandler,
		ApplicationListener<OnShakeEvent> {
	
	private IoHandler login;
	private IoHandler user;
	private IoHandler map;
	private IoHandler raid;
	public IoHandler getRaid() {
		return raid;
	}

	public void setRaid(IoHandler raid) {
		this.raid = raid;
	}

	public IoHandler getMap() {
		return map;
	}

	public void setMap(IoHandler map) {
		this.map = map;
	}

	private Logger logger = Logger.getLogger(getClass());

	@Resource(name = "heartBeatHandler")
	private HeartBeatHandler heartBeatHandler;

	@Override
	public void onApplicationEvent(OnShakeEvent event) {
		Channel channel = event.getChannel();
		login.onShake(channel);	

	}

	@SuppressWarnings("rawtypes")
	@Override
	public void messageReceived(Channel channel, SocketModel message) 
	{
     try 
     {  

		switch (message.getOpDefinde())
		 {
		   
			case Protocol.LogionOption:
				login.messageReceived(channel, message);//到登录模块
				if (message.getCommand() == LoginProtocol.LOGIN_CREQ) 
				{
					heartBeatHandler.received(channel);
				}
				break;
			case Protocol.TYPE_USER:
				user.messageReceived(channel, message);
				break;
			case Protocol.TYPE_MAP:
				map.messageReceived(channel, message);
				break;
			case Protocol.TYPE_RAID:
				raid.messageReceived(channel, message);
				break;
			}
	   } 
		catch (Exception e) 
		{
			logger.error(ErrorUtil.decode(e));
		}

	}

	@Override
	public void channelClose(Channel channel) {	
		try{
		    raid.channelClose(channel);
			map.channelClose(channel);
//			mission.channelClose(channel);
		}catch(Exception e)
		{
			logger.debug(ErrorUtil.decode(e));
		}
		finally
		{
			// 下面三个必须最后调用---因为会清除channel与角色的映射关系
			login.channelClose(channel);//下线
			user.channelClose(channel);
			heartBeatHandler.close(channel);
		}
		
	}

	@Override
	public void onShake(Channel channel) {
		// 总逻辑控制 无需监听 --握手由此class派发

	}
	public IoHandler getUser() {
		return user;
	}
	public void setUser(IoHandler user) {
		this.user = user;
	}
	public IoHandler getLogin() {
		return login;
	}

	public void setLogin(IoHandler login) {
		this.login = login;
	}

	public HeartBeatHandler getHeartBeatHandler() {
		return heartBeatHandler;
	}

	public void setHeartBeatHandler(HeartBeatHandler heartBeatHandler) {
		this.heartBeatHandler = heartBeatHandler;
	}


	
}
